package com.valuedaas.schoolsafety.controller.permission;

import com.mongodb.MongoWriteException;
import com.valuedaas.schoolsafety.common.ErrorCodes;
import com.valuedaas.schoolsafety.common.base.Result;
import com.valuedaas.schoolsafety.common.enums.FixedRoles;
import com.valuedaas.schoolsafety.controller.user.vo.User;
import com.valuedaas.schoolsafety.service.recources.RoleService;
import com.valuedaas.schoolsafety.util.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping(value = "/role/", produces = {"application/json;charset=utf-8"})
@Api(description = "权限管理-角色管理", value = "RoleController")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "获取所有角色列表-(固定就 管理员和普通用户)", notes = "获取所有角色列表-(固定就 管理员和普通用户)")
    @RequestMapping(path = "/all.do", method = RequestMethod.GET)
    public String listAllRole() {
        List<Document> list = roleService.listSocialUnitRoles();
        return Result.ok("角色列表", list);
    }

    @ApiOperation(value = "获取所有固定角色列表", notes = "获取所有固定角色列表")
    @RequestMapping(path = "/fixedroles.do", method = RequestMethod.GET)
    public String lisAllFixedRole() {
        List<String> roleNames = new ArrayList<>();
        for (FixedRoles d : FixedRoles.values()) {
            roleNames.add(d.name());
        }
        List<Document> list = roleService.listSocialUnitRoles(roleNames);
        return Result.ok("角色列表", list);
    }


    @ApiOperation(value = "获取某个角色详情", notes = "获取某个角色详情")
    @RequestMapping(path = "/detail.do", method = RequestMethod.GET)
    public String getRole(@RequestParam(required = true) String id) {
        User user = WebUtil.getSessionUser();
        Document doc = roleService.getSocialUnitRole(id);
        if (doc == null) {
            return Result.error("未找到该角色", null);
        }
        return Result.ok("角色信息", doc);
    }

    @ApiOperation(value = "获取所在单位角色列表（目前修改和all.do一样了，不区分unitId）", notes = "获取所在单位角色列表（目前修改和all.do一样了，不区分unitId")
    @RequestMapping(path = "/list.do", method = RequestMethod.GET)
    public String listRole() {
        // User user = WebUtil.getSessionUser();
        // List<Document> list = roleService.listSocialUnitRoles(user.getUnitId());
        // return Result.ok("角色列表", list);
        List<Document> list = roleService.listSocialUnitRoles();
        return Result.ok("角色列表", list);
    }

    @ApiOperation(value = "添加一个新的角色", notes = "获取所在单位角色列表")
    @RequestMapping(path = "/add.do", method = RequestMethod.POST)
    public String addRole(@RequestParam(required = true) String roleName,
                          @RequestParam(required = true) String roleDesc) {
        User user = WebUtil.getSessionUser();
        String unitId = user.getUnitId();
        if (roleService.checkRoleByName(roleName, unitId)) {
            return Result.error("角色名称重复", null);
        }

        roleService.addRole(roleName, roleDesc, unitId);
        return Result.ok("添加成功", null);
    }

    @ApiOperation(value = "删除本单位某个角色", notes = "删除本单位某个角色")
    @RequestMapping(path = "/delete.do", method = RequestMethod.POST)
    public String deleteRole(@RequestParam(required = true) String roleId) {
        User user = WebUtil.getSessionUser();
        String unitId = user.getUnitId();

        if (roleService.hasRoleUser(unitId, roleId)) {
            return Result.error("该角色还有用户，不能删除", null);
        }

        if (!roleService.deleteRole(unitId, roleId)) {
            return Result.error("该角色不存在", null);
        }

        return Result.ok("删除成功", null);
    }

    @ApiOperation(value = "更新本单位某个角色", notes = "更新本单位某个角色")
    @RequestMapping(path = "/update.do", method = RequestMethod.POST)
    public String updateRole(@RequestParam(required = true) String roleId,
                             @RequestParam(required = true) String roleName, @RequestParam(required = true) String roleDesc) {
        User user = WebUtil.getSessionUser();
        String unitId = user.getUnitId();
        try {
            if (!roleService.updateRole(unitId, roleId, roleName, roleDesc)) {
                return Result.error("该角色不存在", null);
            }
        } catch (MongoWriteException e) {
            return Result.error(ErrorCodes.RESOURCE_DUPLICATE, "角色名称不能重复", "duplicate key error");
        }

        return Result.ok("更新成功", null);
    }

    @ApiOperation(value = "获取某个角色下的所有菜单", notes = "获取某个角色下的所有菜单")
    @RequestMapping(path = "/menus.do", method = RequestMethod.GET)
    public String getRoleMenuList(@RequestParam(required = true) String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            return Result.error("角色ID参数不能为空", null);
        }
        User user = WebUtil.getSessionUser();
        List<ObjectId> menus = roleService.getRoleAuthMenu( roleId);

        return Result.ok("菜单列表", menus);
    }

    /**
     * 设置本单位下的某个角色的授权菜单
     *
     * @param menuIds 菜单ID,以逗号分割 xxxxx,xxxx,xxxx
     * @param roleId  角色ID
     * @return JSON
     */
    @ApiOperation(value = "设置本单位下的某个角色的授权菜单", notes = "设置本单位下的某个角色的授权菜单")
    @RequestMapping(path = "/menu/update.do", method = RequestMethod.POST)
    public String updateRoleMenus(@RequestParam(required = true) String menuIds,
                                  @RequestParam(required = true) String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            return Result.error("角色ID参数不能为空", null);
        }
        User user = WebUtil.getSessionUser();
        String[] menus = menuIds.split("\\,");
        if (!roleService.setRoleAuthMenu(roleId, Arrays.asList(menus))) {
            return Result.error("更新失败", null);
        }

        return Result.ok("更新成功", null);
    }

    @ApiOperation(value = "获得本单位下某个角色的授权接口", notes = "获得本单位下某个角色的授权接口")
    @RequestMapping(path = "/interfaces.do", method = RequestMethod.GET)
    public String getRoleInterfaceList(@RequestParam String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            return Result.error("角色ID参数不能为空", null);
        }
        User user = WebUtil.getSessionUser();
        List<ObjectId> interfaces = roleService.getRoleAuthInterface(roleId);

        return Result.ok("接口列表", interfaces);
    }

    /**
     * 设置本单位下的某个角色的授权接口
     *
     * @param interfaceIds 接口ID,以逗号分割 xxxxx,xxxx,xxxx
     * @param roleId       角色ID
     * @return JSON
     */
    @ApiOperation(value = "设置本单位下的某个角色的授权接口", notes = "设置本单位下的某个角色的授权接口")
    @RequestMapping(path = "/interfaces/update.do", method = RequestMethod.POST)
    public String updateRoleInterface(@RequestParam(required = true) String interfaceIds,
                                      @RequestParam(required = true) String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            return Result.error("角色ID参数不能为空", null);
        }
        User user = WebUtil.getSessionUser();
        String[] interfaces = interfaceIds.split("\\,");
        if (!roleService.setRoleAuthInterface(roleId, Arrays.asList(interfaces))) {
            return Result.error("更新失败", null);
        }

        return Result.ok("更新成功", null);
    }

}
